<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use common\collection\Common;
use common\collection\BackendCommon;
use common\helpers\PublicFun;
use backend\config\routeParams;


/**
 * Pay controller
 */
class PayController extends Controller
{

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public  function beforeAction($action){
        if(BackendCommon::init()){
            return true;
        }else{
            Yii::$app->response->redirect( ['login/index']);
        }
    }

    public function  Test(){
        $VipData = array(
            "OrderId" => 'V17092371628872',
            "PaymentMethod" => 200,
            "PayAccount" => '15861888931',
            "PayNo" => '2017021721001004420276500667',
        );
        $url = routeParams::HttpUrl('PCEnterpriseVersionRenewCallBack');
        $result = PublicFun::PostPackage($VipData, $url);
        var_dump($result);
        exit;
    }

    //
    public function actionPaystatus(){
        $OrderId = Yii::$app->request->get('orderid');
        $post['MytipId'] = Common::GetMytipId();
        $url = routeParams::HttpUrl('PCEnterpriseVersionRenewOrderVerify');
        $JsonData = ['OrderId' => $OrderId];
        $result = PublicFun::PostPackage($JsonData, $url);
        $result = json_decode($result['Body'],true);
        return $this->render('paystatus',array('Info'=>$result));
    }

    //微信支付
    public function actionWebpay(){

        $OrderId = Yii::$app->request->get('orderid');
        $post['MytipId'] = Common::GetMytipId();
        $url = routeParams::HttpUrl('PCEnterpriseVersionRenewOrderVerify');
        $JsonData = ['OrderId' => $OrderId];
        $result = PublicFun::PostPackage($JsonData, $url);
        $result = json_decode($result['Body'],true);

        //生成img

        require_once ('../phpqrcode/phpqrcode.php');
        require_once('../extensions/Wxpay/WxPayPubHelper.php');
        require_once('../extensions/Wxpay/SDKRuntimeException.php');
        require_once('../extensions/Wxpay/WxPay.pub.config.php');
        require_once ('../extensions/Wxpay/jssdk.php');
        header("Content-type: text/html; charset=utf-8");
        $notify_url = 'http://www.boliju.com/pay/wxNotify';
        //=========步骤2：使用统一支付接口，获取prepay_id============
        //使用统一支付接口
        $unifiedOrder = new NativeLink_pub();
        $unifiedOrder->setParameter("product_id",$OrderId);
        $unifiedOrder->setParameter("body",$result['Model']['ENTCode'].'-版本续费-'.$result['Model']['SysVersionName']);              //商品描述
        $unifiedOrder->setParameter("out_trade_no",$OrderId);      //商户订单号
        $unifiedOrder->setParameter("total_fee",$result['Model']['PayAmount']*100);   			   //总金额
        $unifiedOrder->setParameter("notify_url", $notify_url);  //通知地址
        $unifiedOrder->setParameter("trade_type","NATIVE");//交易类型
        $Url = $unifiedOrder->getUrl();
        return $this->render('webpay',array('weixinsrc'=>$Url,'Info'=>$result));

    }

    // 微信支付回掉
    public function actionWxNotify(){
        require_once('../extensions/Wxpay/WxPayPubHelper.php');
        require_once('../extensions/Wxpay/WxPay.pub.config.php');

        //使用通用通知接口
        $notify = new Notify_pub();

        //存储微信的回调
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];

        $notify->saveData($xml);

        //验证签名，并回应微信。
        //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
        //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
        //尽可能提高通知的成功率，但微信不保证通知最终能成功。
        if($notify->checkSign() == FALSE){

            $notify->setReturnParameter("return_code","FAIL");//返回状态码
            $notify->setReturnParameter("return_msg","签名失败");//返回信息
        }else{
            $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
        }
        // exit;
        $returnXml = $notify->returnXml();
        //==商户根据实际情况设置相应的处理流程，此处仅作举例=======
        //商户自行增加处理流程,
        //例如：更新订单状态
        if ($notify->data["return_code"] == "SUCCESS" && $notify->data['result_code']=='SUCCESS') {
            $OrderId = $notify->data["out_trade_no"];
            $Data = array(
                "OrderId" => $OrderId,
            );
            $url = routeParams::HttpUrl('PCEnterpriseVersionRenewOrderVerify');
            $result = PublicFun::PostPackage($Data, $url);
            $result = json_decode($result['Body'], true);
            if($result['Model']['IsPay']){
                exit;
            }
            $VipData = array(
                "OrderId" => $OrderId,
                "PaymentMethod" => 300,
                "PayAccount" => $notify->data["openid"],
                "PayNo" => $notify->data["transaction_id"],
            );
            $url = routeParams::HttpUrl('PCEnterpriseVersionRenewCallBack');
            $result = PublicFun::PostPackage($VipData, $url);
            echo "SUCCESS";
        }
    }

    //支付宝支付
    public function actionAlipay()
    {
        require_once('../extensions/Alipay/alipay.config.php');
        require_once('../extensions/Alipay/lib/alipay_submit.class.php');
        $OrderId = Yii::$app->request->get('orderid');
        $post['MytipId'] = Common::GetMytipId();
        $url = routeParams::HttpUrl('PCEnterpriseVersionRenewOrderVerify');
        $JsonData = ['OrderId' => $OrderId];
        $result = PublicFun::PostPackage($JsonData, $url);
        $result = json_decode($result['Body'],true);

        /**************************请求参数**************************/
        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $OrderId ;
        //订单名称，必填
        $subject = $result['Model']['ENTCode'].'-版本续费-'.$result['Model']['SysVersionName'];

        //付款金额，必填
        $total_fee = $result['Model']['PayAmount'];
        $notify_url = 'http://www.boliju.com/pay/alipaynotify';
        $return_url = 'http://www.boliju.com/pay/status';

        //商品描述，可空
        /*   $body = $_POST['WIDbody'];*/
        /************************************************************/

        //构造要请求的参数数组，无需改动
        $parameter = array(
            "service"       => $alipay_config['service'],
            "partner"       => $alipay_config['partner'],
            "seller_id"     => $alipay_config['seller_id'],
            "payment_type"	=> $alipay_config['payment_type'],
            "notify_url"	=> $notify_url,
            "return_url"	=> $return_url,
            "anti_phishing_key"=>$alipay_config['anti_phishing_key'],
            "exter_invoke_ip"=> $alipay_config['exter_invoke_ip'],
            "out_trade_no"	 => $out_trade_no,
            "subject"	     => $subject,
            "total_fee"	     => $total_fee,
            /*	"body"	         => $body,*/
            "_input_charset" => trim(strtolower($alipay_config['input_charset']))
            //其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.kiX33I&treeId=62&articleId=103740&docType=1
            //如"参数名"=>"参数值"
        );
        //建立请求
        $alipaySubmit = new AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
        echo $html_text;
    }
    //支付宝异步回调
    function  actionAlipayNotify(){
        require_once('../extensions/Alipay/alipay.config.php');
        require_once('../extensions/Alipay/lib/alipay_notify.class.php');
        //计算得出通知验证结果
        $alipayNotify = new AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyNotify();
        if($verify_result) { //验证成功
            //商户订单号
            $out_trade_no = $_POST['out_trade_no'];
            //支付宝交易号
            $trade_no = $_POST['trade_no'];
            $buyer_email = $_POST['buyer_email'];
            $total_fee  = $_POST['total_fee'];
            //交易状态
            $trade_status = $_POST['trade_status'];

            if($_POST['trade_status'] == 'TRADE_FINISHED' || $_POST['trade_status'] == 'TRADE_SUCCESS') {
                $Data = array(
                    "OrderId" => $out_trade_no,
                );
                $url = routeParams::HttpUrl('PCEnterpriseVersionRenewOrderVerify');
                $result = PublicFun::PostPackage($Data, $url);
                $result = json_decode($result['Body'], true);
                if($result['Model']['IsPay']){
                    exit;
                }
                $VipData = array(
                    "OrderId" => $out_trade_no,
                    "PaymentMethod" => 200,
                    "PayAccount" => $buyer_email,
                    "PayNo" => $trade_no,
                );
                $url = routeParams::HttpUrl('PCEnterpriseVersionRenewCallBack');
                $result = PublicFun::PostPackage($VipData, $url);
            }
            echo "success";		//请不要修改或删除
        }else {

            echo "fail";
        }
    }
    function actionStatus(){
        require_once('../extensions/Alipay/alipay.config.php');
        require_once('../extensions/Alipay/lib/alipay_notify.class.php');
        //计算得出通知验证结果
        $alipayNotify = new AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyReturn();
        //商户订单号
        $out_trade_no = $_GET['out_trade_no'];
        if($verify_result) {
            $this->redirect('/pay/paystatus?orderid='.$out_trade_no);
        }else {
            $this->redirect('/pay/paystatus?orderid='.$out_trade_no);
        }

    }


    //支付前验证
    public function actionIsPaid()
    {
        $JsonData = Yii::$app->request->post();
        //数据过滤
        $JsonData = Common::ArrayFilter($JsonData);
        $JsonData['MytipId'] =  Common::GetMytipId();
        $url = routeParams::HttpUrl('PCEnterpriseVersionRenewOrderVerify');
        $result = PublicFun::PostPackage($JsonData, $url);
        $result = $result = json_decode($result['Body'],true);
        die(json_encode($result));
    }


}
